import * as vscode from "vscode";
import { translate } from "../util.js";
import { createStatus } from "../vsUtil.js";


export default (context: vscode.ExtensionContext) => {

  // 状态栏对象
  const states: vscode.StatusBarItem = createStatus({
    name: "myStatus",
    text: "$(sync~spin)loading...",
    tooltip: "正在翻译"
  });

  const disposable = vscode.commands.registerTextEditorCommand("an-tools.translate", async (textEditor: vscode.TextEditor, edit: vscode.TextEditorEdit) => {
    // 获取当前选中的文本
    const text = textEditor.document.getText(textEditor.selection);

    if (!text.trim()) {
      vscode.window.showErrorMessage("没有选中文本哦");
      return;
    }

    // if (/^[\u4e00-\u9fa5]{0,}$/.test(text)) {
    //  vscode.window.showWarningMessage("请选择英文");
    //   return;
    // }

    states.show();

    try {
      const res: ObjectType = await translate(text);
      if (res.errorCode === 0) {
        const value = res.translateResult[0][0].tgt;
        vscode.window.showInformationMessage(`翻译结果为:【 ${value} 】`, "复制").then((res: string | undefined) => {
          if (res === "复制") {
            vscode.env.clipboard.writeText(value);
          }
        });
      } else {
        vscode.window.showErrorMessage("翻译失败");
      }
    } catch (error: unknown) {
      const tip = (msg: string) => vscode.window.showErrorMessage(msg);
      if (error instanceof Error) {
        tip(error.message || "翻译错误");
      } else {
        tip("翻译错误");
      }
    } finally {
      states.hide();
    }
  });
  context.subscriptions.push(disposable);
}